package com.novellotus.iov.carvice.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.adapter.RoleHelpAdapter;
import com.novellotus.iov.carvice.bean.RxFn;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import okhttp3.RequestBody;

public class EditEmployeeActivity extends BaseActivity {

    @BindView(R.id.edt_name)
    EditText edt_name;
    @BindView(R.id.nice_spinner)
    NiceSpinner nice_spinner;
    @BindView(R.id.edt_mark)
    EditText edt_mark;
    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.btn_right)
    Button btn_right;
    @BindView(R.id.btn_submit)
    Button btn_submit;

    private String eCode = "", rCode = "", name = "", roleId = "", mark = "", id = "", userId = "";
    private ArrayList<RxFn> rxFnList;

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_edit_employee);
    }

    @Override
    public void init() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            eCode = bundle.getString("e");
            rCode = bundle.getString("r");
            name = bundle.getString("name");
            roleId = bundle.getString("roleId");
            mark = bundle.getString("mark");
            id = bundle.getString("id");
            userId = bundle.getString("userId");
            rxFnList = bundle.getParcelableArrayList("roleList");
            edt_name.setText(name);
            edt_mark.setText(mark);
        }


        if (rxFnList != null) {
            initSpinner();
        }

        tv_tittle.setText("修改员工信息");
        btn_right.setTextColor(Color.parseColor("#ffffff"));
        setNameEdit();
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.btn_submit)
    void editUser() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("nickName", edt_name.getText().toString());
        jsonObject.addProperty("roleId", roleId);
        jsonObject.addProperty("remark", edt_mark.getText().toString());
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("text/plain; charset=utf-8"), jsonObject.toString());
        Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().editStaff(id, SharedPreferencesUtils.getKey(this)[0], eCode, rCode, body);
        observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                .subscribe(new BaseObserver<Object>(this) {
                    @Override
                    public void onSuccess(Object rxFindUser) {
                        MyUtils.showToast(EditEmployeeActivity.this, "修改成功!");
                        finish();
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        MyUtils.showToast(EditEmployeeActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(EditEmployeeActivity.this, msg);
                    }
                });
    }

    AlertDialog alertDialog;

    @OnClick(R.id.btn_right)
    void removeStaff() {
        if (!userId.equals(SharedPreferencesUtils.getUser(EditEmployeeActivity.this)[3])) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            alertDialog = builder.create();
            builder.setMessage("确定移除员工:" + name + "?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    Observable<BaseEntity<Object>> observable = RetrofitFactory.getInstance().removeStaff(id, SharedPreferencesUtils.getKey(EditEmployeeActivity.this)[0], eCode, rCode);
                    observable.compose(RxSchedulers.<BaseEntity<Object>>compose())
                            .subscribe(new BaseObserver<Object>(EditEmployeeActivity.this) {
                                @Override
                                public void onSuccess(Object rxFindUser) {
                                    MyUtils.showToast(EditEmployeeActivity.this, "移除成功!");
                                    finish();
                                }

                                @Override
                                public void onFail(int code, String msg) {
                                    MyUtils.showToast(EditEmployeeActivity.this, msg);
                                }

                                @Override
                                public void onError(String msg) {
                                    MyUtils.showToast(EditEmployeeActivity.this, msg);
                                }
                            });

                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    alertDialog.dismiss();
                }
            });
            builder.show();
        }
    }


    @OnClick(R.id.img_help)
    void showHelp() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_role_detail, null);
        RecyclerView recyclerView = view.findViewById(R.id.recycler);
        recyclerView.setLayoutManager(MyViewUtils.getLinearLayoutManager(this));
        recyclerView.setAdapter(new RoleHelpAdapter(rxFnList));
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("角色权限");
        builder.setView(view);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        builder.show();
    }

    /**
     * 设置邮箱编辑框
     */
    private void setNameEdit() {
        RxTextView.textChanges(edt_name).subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                if (value.length() == 0) {
                    MyViewUtils.setButtonClickable(btn_submit, false);
                } else {
                    MyViewUtils.setButtonClickable(btn_submit, true);
                }
            }
        });
    }

    private void initSpinner() {
        int roleIndex = 0;
        List<String> dataset = new LinkedList<>();
        for (int i = 0; i < rxFnList.size(); i++) {
            dataset.add(rxFnList.get(i).getRoleName());
            if (rxFnList.get(i).getRoleId().equals(roleId)) {
                roleIndex = i;

            }
        }
        if (dataset.size() == 1) {
            nice_spinner.hideArrow();
        } else {
            nice_spinner.showArrow();
        }
        nice_spinner.attachDataSource(dataset);
        nice_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                roleId = rxFnList.get(i).getRoleId();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        nice_spinner.setSelectedIndex(roleIndex);
        if (userId.equals(SharedPreferencesUtils.getUser(this)[3])) {
            nice_spinner.setEnabled(false);
            nice_spinner.hideArrow();
        } else {
            btn_right.setText("移除员工");
        }
    }
}
